import { getinquiries } from '@/api/service';
import { env, inquiryLink, resultLink } from '@/common/baseUrl.js';

export const inquiryMixin = {
  methods: {
    /**
     * @description - 服务包问询跳转
     * @param {Object} data
     * @param {object[]} data.insuranceServices - 服务产品信息
     * @param {string} data.teamOrderNo - 服务单单号
     * @param {string} data.insuredId - 被保险人ID
     * @param {string} data.packageId - 服务产品ID
     * @returns
     */
    async inquiryMixin(data) {
      if (!data) throw new Error('请传入data数据! 相关参数请参考注释文档!');
      const { insuranceServices = [], teamOrderNo, insuredId, packageId, orderId } = data;
      if (!insuranceServices.length) throw new Error('请传入data.insuranceServices(服务产品信息)为Array类型');
      if (!insuredId) throw new Error('请传入data.insuredId(被保险人ID)');
      if (!packageId) throw new Error('请传入data.packageId(服务产品ID)');
      if (!orderId) throw new Error('请传入data.orderId(服务订单ID)');

      const token = uni.getStorageSync('token');
      const packType = insuranceServices.map((item) => item.type || item.productType);
      const includeInsurance = insuranceServices.some((item) => item.type === 1 || item.productType === 1); // 是否含保险
      let linkUrl;

      // 是否含保险
      if (includeInsurance) {
        if (!teamOrderNo) throw new Error('请传入data.teamOrderNo(保险服务单号)'); // 如果有保险则必传

        const q = await getinquiries(packageId);
        if (q.code !== 0 || !q.data) {
          uni.showToast({
            title: q.message || '服务部查询错误',
            icon: 'none'
          });
          throw new Error(q.message || '服务部查询错误');
        }
        const dtoName = insuranceServices.find((item) => item.type === 1 || item.productType === 1);
        const serviceName = dtoName.serviceName || dtoName.productName;

        const resultView = `${resultLink}?packType=${packType}&serviceName=${serviceName}&insuredId=${insuredId}&orderId=${orderId}&token=${token}&e=${env}&result=1`;

        /**
         * 如果有问询, 则跳转至问询页面, 如没有则直接到结果页面
         */
        if (q.data.needInquiry) {
          linkUrl = `${inquiryLink}?e=${env}&packageId=${packageId}&packType=${packType}&teamOrderNo=${teamOrderNo}&token=${token}&backLink=${encodeURIComponent(
            resultView
          )}`;
        } else {
          linkUrl = resultView;
        }
      } else {
        linkUrl = `${resultLink}?packType=${packType}&insuredId=${insuredId}&orderId=${orderId}&token=${token}&e=${env}&result=1`;
      }

      this.$wxPromise.navigateTo({
        url: '/pages/view/web-view?url=' + encodeURIComponent(linkUrl)
      });
    }
  }
};
